﻿using Sx.Core;
using Sx.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sx.Web.Admin.Areas.Sys.Models
{
    public class MenuService : BaseService
    {
        public MenuService() : base("Default", "sys_menus", "菜单表")
        {
        }

        public List<object> GetAllMenusForDS()
        {
            var menuList = GetList<dynamic>(new { }, "menu_id,name,icon,url,parent_id,sort", "sort");
            List<object> result = GetChilds(0, menuList);
            return result;
        }

        private List<object> GetChilds(long pid, List<dynamic> ds)
        {
            List<object> result = new List<object>();
            var menus = ds.Where(d => d.parent_id == pid).OrderBy(d => d.sort).ToList();
            foreach (var menu in menus)
            {
                var children = GetChilds(CommonHelper.ToInt64( menu.menu_id), ds);
                if (children.Count > 0)
                {
                    result.Add(new { id = menu.menu_id, iconCls = menu.icon, text = menu.name, url = menu.url, children = children });
                }
                else
                {
                    result.Add(new { id = menu.menu_id, iconCls = menu.icon, text = menu.name, url = menu.url, });
                }
            }
            return result;
        }
    }
}
